package grg.learn.demoframework

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

abstract class CC : LifecycleEventObserver {

    companion object {

        /**
         * create by iso88591 at 2022/2/10
         * 通过这种方式 把一个lamda转化成了一个匿名对象
         */
        inline operator fun invoke(crossinline block: @Composable ComposeActivity.() -> Unit) =
            object : CC() {
                @Composable
                override fun ComposeActivity.Compose() {
                    block()
                }
            }
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
    }

    @Composable
    abstract fun ComposeActivity.Compose()

}

class ComposeActivity : ComponentActivity() {

    companion object {
        fun start(context: Context, ccClass: Class<out CC>) {
            context.startActivity(Intent(context, ComposeActivity::class.java).also {
                it.putExtra("CCClass", ccClass)
            })
        }

        operator fun invoke(context: Context, ccClass: Class<out CC>) {
            start(context, ccClass)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val ccClass = intent.getSerializableExtra("CCClass") as Class<out CC>
        val cc = ccClass.newInstance()
        lifecycle.addObserver(cc)
        setContent {
            cc.apply {
                Compose()
            }
        }
    }

}